// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// To make sure we can uniquely identify each screenshot tab, add an id as a
// query param to the url that displays the screenshot.
// Note: It's OK that this is a global variable (and not in localStorage),
// because the event page will stay open as long as any screenshot tabs are
// open.
var id = 100;

// Listen for a click on the camera icon. On that click, take a screenshot.
chrome.browserAction.onClicked.addListener(function() {
  // Code to send message to content script to display UI components in live
  // view for the user to interact with
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    chrome.tabs.sendMessage(tabs[0].id, {greeting: "launchUI"});
  });
  
});

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    if (request.greeting == "cropImage") {
      chrome.tabs.captureVisibleTab(function(screenshotUrl) {
        var viewTabUrl = chrome.extension.getURL('screenshot.html?id=' + id++)
        var targetId = null;
        var croppedCanvas = document.createElement('canvas');
        croppedCanvas.width = request.width;
        croppedCanvas.height = request.height;
        var context = croppedCanvas.getContext('2d');
        var imageObj = new Image();
        imageObj.onload = function() {
            //crop image
            context.drawImage(imageObj, request.x, request.y, request.width, request.height, 0, 0, request.width, request.height);
            getDate();
            chrome.downloads.download({
                url: croppedCanvas.toDataURL(),
                filename: 'IMG_'+ suffix + '.png'
            });
        };
        imageObj.src = screenshotUrl;
      });
    } else if (request.greeting == "getButtons") {
      $.ajax({
        url: chrome.extension.getURL("buttons.html"),
        dataType: "html",
        success: sendResponse
      });
      return true;
    }
  }
);


function getDate(){
  var date = new Date();
  suffix = "";
  suffix = suffix + addZero(date.getMonth() + 1);
  suffix = suffix + addZero(date.getDate());
  suffix = suffix + date.getFullYear() + "_";
  suffix = suffix + addZero(date.getHours());
  suffix = suffix + date.getMinutes();
  suffix = suffix + addTwoZero(date.getMilliseconds());
}

function addZero(value) {
    return value < 10 ? '0' + value : value;
}

function addTwoZero(value) {
    if(value < 10){
      return '00' + value;
    }else if(value < 100){
      return '0' + value;
    }else{

      return value;
    }
}